package com.iwith.dongmoon.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.iwith.dongmoon.gsonlist.BoardList;
import com.iwith.dongmoon.gsonlist.BoardListItem;
import com.iwith.dongmoon.listadpater.CommentListAdapter;
import com.iwith.dongmoon.util.ApiCode;
import com.iwith.dongmoon.util.HttpRequestor;
import com.iwith.dongmoon.util.RequestGson;
import com.iwith.dongmoon.util.ResultCode;
import com.iwith.dongmoon.util.ThreadInterface;
import com.iwith.dongmoon.util.ThreadTask;

public class BoardDetailActivity extends Activity implements OnClickListener{
	/** Called when the activity is first created. */
	public static final int REQUEST_GALLERY = 1;
	public static final int REQUEST_CAMERA = 0;
	private RequestGson requestGson = new RequestGson();

	private Intent mIntent;
	private Integer wr_id;
	private String boardname;
	private String userid;

	private TextView typename;
	private TextView subject;
	private TextView name;
	private TextView datetime;
	private WebView content;
	private TextView prevBt;

	private Button favoriteBt;

	private EditText commentBox;
	private Button commitCommentBt;

	private Context mContext;

	private LinearLayout commentLayout;
	private ListView commentList;

	private View mHeader;
	private View mFooter;

	private boolean justOnceFlag = false;
	
	private ImageView title;
	private ImageButton btn_addCommentImage;
	private File imageFile;
	private AlertDialog.Builder mAlertDialog;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.boarddetail);
		mHeader = getLayoutInflater().inflate(R.layout.boarddetail_headerview, null, false);
		mFooter = getLayoutInflater().inflate(R.layout.boarddetail_footerview, null, false);
	}

	@Override
	public void onResume() {
		super.onResume();
		ThreadTask.onFinishAll();
		Initialize();
	}

	@Override
	public void onPause() {
		super.onPause();
		ThreadTask.onFinishAll();
	}

	private void Initialize() {
		mIntent = getIntent();
		wr_id = mIntent.getExtras().getInt("wr_id");
		userid = mIntent.getExtras().getString("userid");
		boardname = mIntent.getExtras().getString("boardname");
		
		mContext = this;
		prevBt = (TextView) findViewById(R.id.backbtn);
		title = (ImageView) findViewById(R.id.title);
		
		typename = (TextView) mHeader.findViewById(R.id.boarddetail_typename);
		subject = (TextView) mHeader.findViewById(R.id.boarddetail_subject);
		name = (TextView) mHeader.findViewById(R.id.boarddetail_name);
		datetime = (TextView) mHeader.findViewById(R.id.boarddetail_datetime);
		content = (WebView) mHeader.findViewById(R.id.boarddetail_content);

		commentList = (ListView) findViewById(R.id.boarddetail_commentlist);
		commentLayout = (LinearLayout) mFooter.findViewById(R.id.boarddetail_commentlayout);
		favoriteBt = (Button) mFooter.findViewById(R.id.boarddetail_favoriteBt);
		commentBox = (EditText) commentLayout.findViewById(R.id.boarddetail_commentbox);
		commitCommentBt = (Button) commentLayout.findViewById(R.id.boarddetail_writecomment);
		btn_addCommentImage = (ImageButton) commentLayout.findViewById(R.id.boarddetail_addcommentimage);
		mAlertDialog = new AlertDialog.Builder(this);
		if (justOnceFlag == false) {
			justOnceFlag = true;
			commentList.addHeaderView(mHeader);
			commentList.addFooterView(mFooter);
		}

		setData(boardname);

		title.setOnClickListener(this);
		prevBt.setOnClickListener(this);
		commitCommentBt.setOnClickListener(this);		
		favoriteBt.setOnClickListener(this);
		btn_addCommentImage.setOnClickListener(this);
	}
	
	private void setData(final String code) {
		ThreadInterface threadInterface = new ThreadInterface() {
			BoardList boardList;
			BoardList boardList2;
			BoardList boardList3;
			String mTitle=null;

			public void onThread() {
				String api = null;
				if (code.equals(ApiCode.NOTICES) == true) {
					api = ApiCode.API_NOTICE;
					mTitle="[ 공지사항 ]";
//				} else if (code.equals(ApiCode.OCCASIONS) == true) {
//					api = ApiCode.API_OCCASION;
//					mTitle="[ 경조사 ]";
//				} else if (code.equals(ApiCode.MEETINGS) == true) {
//					api = ApiCode.API_MEETING;
//					mTitle="[ 모임 ]";
//				} else if (code.equals(ApiCode.ADVERTISEMENTS) == true) {
//					api = ApiCode.API_ADVERTISEMENT;
//					mTitle="[ 업체 홍보 ]";
//				} else if (code.equals(ApiCode.GROUP) == true) {
//					api = ApiCode.API_GROUP;
//					mTitle="[ 소모임 ]";
				} else if (code.equals(ApiCode.BULLETINS) == true) {
					api = ApiCode.API_BULLETIN;
					mTitle="[ 자유게시판 ]";
				} else if (code.equals(ApiCode.NEWS) == true) {
					api = ApiCode.API_NEWS;
					mTitle="[ 소식란 ]";
				}
				
				boardList = requestGson.getBoardGsonBySendingAPI(mContext, api, "GET", "/" + wr_id.toString());
				boardList2 = requestGson.getBoardGsonBySendingAPI(mContext, api + ApiCode.API_COMMENTS, "GET",	"?wr_id=" + wr_id.toString());
				
//				if (code.equals(ApiCode.OCCASIONS) == true
//						|| code.equals(ApiCode.MEETINGS) == true
//						|| code.equals(ApiCode.ADVERTISEMENTS) == true) {
//
//					boardList3 = requestGson.getBoardGsonBySendingAPI(mContext, ApiCode.API_ISFAVORITENEWS, "GET",
//							"?userid=" + userid + "&board=" + boardname + "&index="	+ wr_id.toString());
//
//				} else if (code.equals(ApiCode.NOTICES) == true) {
					boardList3 = null;
//				}
			}

			public void onThreadEnd() {
				//--------------------------------------board data part--------------------------------------
				if (boardList.getResultCode().equals(ResultCode.SUCCESS) == true) {
					typename.setText(mTitle);
					
					if (boardList.getContent().getCa_name() != null && boardList.getContent().getCa_name().equals("") == false) {
						subject.setText("["
								+ boardList.getContent().getCa_name() + "] "
								+ boardList.getContent().getWr_subject());
					} else {
						subject.setText(boardList.getContent().getWr_subject());
					}

					name.setText(boardList.getContent().getWr_name());
					datetime.setText(boardList.getContent().getWr_datetime());
					//content.setNetworkAvailable(true);
					content.loadDataWithBaseURL("http://dongmoonapp.com", boardList.getContent().getWr_content(), "text/html", "UTF-8", null);

					content.getSettings().setDefaultFontSize(16);
				} else {
					requestGson.alertToast(mContext, code + " 데이터 로딩 실패");
				}
				//--------------------------------------comment data part--------------------------------------
				if (boardList2.getResultCode().equals(ResultCode.SUCCESS) == true) {
					ListAdapter listadapter = new CommentListAdapter(mContext, R.id.boarddetail_commentlist, (ArrayList<BoardListItem>) boardList2.getList());
					commentList.setAdapter(listadapter);
				} else {
					requestGson.alertToast(mContext, code + "댓글 데이터 로딩 실패");
				}
				
				//--------------------------------------favorite button data part--------------------------------------
				if (boardList3 == null) {
					favoriteBt.setVisibility(View.GONE);
//				} else if (boardList3.getResultCode().equals(ResultCode.SUCCESS) == true) {
//					favoriteBt.setText("관심 소식에서 지우기");
//					favoriteBt.setTag(ApiCode.DELETEFAVORITENEWS);
//				} else if (boardList3.getResultCode().equals(ResultCode.SUCCESS) == false) {
//					favoriteBt.setText("관심 소식에 추가하기");
//					favoriteBt.setTag(ApiCode.ADDFAVORITENEWS);
//				} else {
//					requestGson.alertToast(mContext, code + " 데이터 로딩 실패");
				}

			}
		};

		ThreadTask mTask = new ThreadTask((Activity) mContext, threadInterface);
		mTask.execute();
	}

	@TargetApi(8)
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK)
			return;

		if (requestCode == REQUEST_GALLERY) {
			Uri imageUri = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String filePath = cursor.getString(columnIndex);
			cursor.close();

			Bitmap bitmap = BitmapFactory.decodeFile(filePath);// , option);
			btn_addCommentImage.setBackgroundDrawable(new BitmapDrawable(bitmap));
			btn_addCommentImage.setImageDrawable(null);			
			
			// 이미지 생성
			File imageFile = new File(filePath);

			File path = null;
			String state = Environment.getExternalStorageState();
			if (state.equals(Environment.MEDIA_MOUNTED)) {
				path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
			} else {
				path = getFilesDir();
			}
			if (!path.exists())
				path.mkdirs();

			this.imageFile=imageFile;
			//uploadPicture(imageFile, thumbnailFile);

		} else if (requestCode == REQUEST_CAMERA) {
			// intent 의 여분 데이터로 저장된 비트맵 이미지를 얻는다. Bitmap bitmap = (Bitmap)
			Bitmap bitmap = (Bitmap) data.getExtras().get("data");
			btn_addCommentImage.setBackgroundDrawable(new BitmapDrawable(bitmap));
			btn_addCommentImage.setImageDrawable(null);
			
			
			File path = null;
			String state = Environment.getExternalStorageState();
			if (state.equals(Environment.MEDIA_MOUNTED)) {
				path = Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
			} else {
				path = getFilesDir();
			}
			if (!path.exists())
				path.mkdirs();

			File imageFile = new File(path, "iwith_image_" + userid + ".jpg");

			FileOutputStream imageOut = null;
			try {
				imageOut = new FileOutputStream(imageFile.getPath());
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (imageOut != null) {
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, imageOut);
			}

			this.imageFile=imageFile;
			//uploadPicture(imageFile, thumbnailFile);
		}
	}
	
	private void commitComment(final String comment_id, final String code) {
		if (commentBox.getText().toString() == null	|| commentBox.getText().toString().length() == 0) {
			requestGson.alertToast(mContext, "댓글을 입력해주세요");
			return;
		} else {
			ThreadInterface threadInterface = new ThreadInterface() {
				BoardList boardList;

				public void onThread() {
					// TODO Auto-generated method stub
					HttpRequestor data = null;
					try {
						String api = null;
						if (code.equals(ApiCode.NOTICES) == true) {
							api = ApiCode.API_NOTICE;
//						} else if (code.equals(ApiCode.OCCASIONS) == true) {
//							api = ApiCode.API_OCCASION;
//						} else if (code.equals(ApiCode.MEETINGS) == true) {
//							api = ApiCode.API_MEETING;
//						} else if (code.equals(ApiCode.ADVERTISEMENTS) == true) {
//							api = ApiCode.API_ADVERTISEMENT;
//						} else if (code.equals(ApiCode.GROUP) == true) {
//							api = ApiCode.API_GROUP;
						} else if (code.equals(ApiCode.BULLETINS) == true) {
							api = ApiCode.API_BULLETIN;
						} else if (code.equals(ApiCode.NEWS) == true) {
							api = ApiCode.API_NEWS;
						}
						data = new HttpRequestor(new URL(getString(R.string.api_url) + api + ApiCode.API_INSERTCOMMENT));
					} catch (MalformedURLException e) {
						e.printStackTrace();
					}
					Gson gson = new Gson();
					data.addParameter("userid", userid);
					data.addParameter("wr_id", wr_id.toString());
					data.addParameter("content", commentBox.getText().toString());
					if (comment_id != "") {
						data.addParameter("comment_id", comment_id);
					}
					data.addFile("picture", imageFile);
					try {
						InputStream is = data.sendMultipartPost((Activity) mContext);
						BufferedReader bin = new BufferedReader(new InputStreamReader(is));
						String line = bin.readLine();
						boardList = gson.fromJson(line, BoardList.class);
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
					}
//					String sresult = data.getDataPost();
//					boardList = gson.fromJson(sresult, BoardList.class);
				}

				public void onThreadEnd() {
					// TODO Auto-generated method stub
					if (boardList.getResultCode().equals(ResultCode.SUCCESS) == false) {
						requestGson.alertToast(mContext, "댓글 입력 실패");
						return;
					} else if (boardList.getResultCode().equals(ResultCode.SUCCESS) == true) {
						requestGson.alertToast(mContext, "댓글 입력 성공");
						imageFile = null;
						btn_addCommentImage.setImageDrawable(getResources().getDrawable(android.R.drawable.ic_menu_gallery));
						btn_addCommentImage.setBackgroundResource(R.drawable.btn_default);
						commentBox.setText("");
						setData(boardname);
					}
				}

			};
			ThreadTask mTask = new ThreadTask((Activity) mContext, threadInterface);
			mTask.execute();
		}
	}
	
//	private void setFavorite(final String code) {
//		BoardList boardList = null;
//		if (code.equals(ApiCode.DELETEFAVORITENEWS) == true) {
//			Gson gson = new Gson();
//			RequestData data = new RequestData(mContext, ApiCode.API_DELETEFAVORITENEWS, "POST", "");
//			data.addParameter("userid", userid);
//			data.addParameter("board", boardname);
//			data.addParameter("index", wr_id.toString());
//			String sresult = data.getDataPost();
//			boardList = gson.fromJson(sresult, BoardList.class);
//		} else if (code.equals(ApiCode.ADDFAVORITENEWS) == true) {
//			Gson gson = new Gson();
//			RequestData data = new RequestData(mContext, ApiCode.API_ADDFAVORITENEWS, "POST", "");
//			data.addParameter("userid", userid);
//			data.addParameter("board", boardname);
//			data.addParameter("index", wr_id.toString());
//			String sresult = data.getDataPost();
//			boardList = gson.fromJson(sresult, BoardList.class);
//		}
//
//		if (boardList.getResultCode().equals(ResultCode.SUCCESS) == true) {
//			if (code.equals(ApiCode.ADDFAVORITENEWS) == true) {
//				favoriteBt.setText("관심 소식에서 지우기");
//				favoriteBt.setTag(ApiCode.DELETEFAVORITENEWS);
//			} else if (code.equals(ApiCode.DELETEFAVORITENEWS) == true) {
//				favoriteBt.setText("관심 소식에 추가하기");
//				favoriteBt.setTag(ApiCode.ADDFAVORITENEWS);
//			}
//		} else {
//			if (code.equals(ApiCode.ADDFAVORITENEWS) == true) {
//				requestGson.alertToast(mContext, "관심소식 추가하기 실패");
//			} else if (code.equals(ApiCode.DELETEFAVORITENEWS) == true) {
//				requestGson.alertToast(mContext, "관심소식 지우기 실패");
//			}
//		}
//
//	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v.getId()==title.getId()){
			Intent intent=new Intent(this, MainIconView.class);
			intent.putExtra("flag", true);
			startActivity(intent);
		} else if(v.getId()==prevBt.getId()){
			finish();
		} else if(v.getId()==commitCommentBt.getId()){
			commitComment("", boardname);
		} else if(v.getId()==favoriteBt.getId()){
			String tag=(String)v.getTag();
//			setFavorite(tag);
		} else if(v.getId()==btn_addCommentImage.getId()){
			final String items[] = { "앨범에서 불러오기", "찍어서 올리기", "취소" };
			mAlertDialog.setTitle("사진등록하기");
			mAlertDialog.setSingleChoiceItems(items, 0,	new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					Intent intent = null;
					switch (whichButton) {
					case 0:
						intent = new Intent(Intent.ACTION_PICK);
						intent.setType("image/*");
						startActivityForResult(intent, REQUEST_GALLERY);
						break;

					case 1:
						intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						startActivityForResult(intent, REQUEST_CAMERA);
						break;
					}
					dialog.dismiss();
				}
			});
			mAlertDialog.show();
		}
	}
}
